import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRouters } from '@/router'

const whitelist = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log(res.roles.menus)
        // console.log(asyncRouters)

        const filterRoutes = asyncRouters.filter(item => {
          // console.log(item.children)
          return res.roles.menus.includes(item.children[0].name)
        })
        console.log(filterRoutes)
        store.commit('user/setRouters', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    whitelist.includes(to.path) ? next() : next('/login')
  }

  NProgress.done()
})
